package me.gavin.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import me.gavin.BR

abstract class BaseFragment : PerceptibleFragment() {

    abstract val layoutId: Int

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(layoutId, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        afterCreate(savedInstanceState)
    }

    abstract fun afterCreate(savedInstanceState: Bundle?)

    open fun doSomething() {} // 预留

}

abstract class BindingFragment<B : ViewDataBinding> : BaseFragment() {

    lateinit var binding: B
        private set

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = initDataBinding(inflater, container)
        binding.lifecycleOwner = this
        return binding.root
    }

    protected open fun initDataBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): B {
        return DataBindingUtil.inflate(inflater, layoutId, container, false)
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.unbind()
    }

}

abstract class BindingVMFragment<B : ViewDataBinding> : BindingFragment<B>() {

    abstract val viewModel: BaseViewModel

    override fun initDataBinding(inflater: LayoutInflater, container: ViewGroup?): B {
        return super.initDataBinding(inflater, container).also {
            it.setVariable(BR.vm, viewModel)
        }
    }

}